const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const os = require('os');

let intervalId;

const createWindow = () => {
    const win = new BrowserWindow({
        width: 320,
        height: 800,
        hasShadow: false,
        // x: 0,
        // y: 900,
        frame: false,
        transparent: true,
        alwaysOnTop: true,
        icon: path.join(__dirname, 'icons/icon.png'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: false,
        }
    })
    // win.webContents.openDevTools()
    win.setIgnoreMouseEvents(false)
    win.loadFile('index.html')

    // 开始监测CPU使用情况
    startMonitoring();
}

ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    win.setIgnoreMouseEvents(ignore, options)
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

app.on('before-quit', () => {
    // 停止监测CPU使用情况
    clearInterval(intervalId);
});

app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

function startMonitoring() {
    intervalId = setInterval(() => {
        const cpuUsage = os.loadavg()[0];
        const userCpuUsage = os.loadavg()[1];

        // 获取系统内存信息
        const totalMemory = os.totalmem();
        const usedMemory = totalMemory - os.freemem();
        const mainWindow = BrowserWindow.getAllWindows()[0]
        // 发送CPU使用情况给渲染进程
        mainWindow.webContents.send('cpu-usage', {
            cpuUsage, userCpuUsage, totalMemory: formatBytes(totalMemory), usedMemory: formatBytes(usedMemory)
        });
    }, 7000);
}

// 格式化字节为可读格式
function formatBytes(bytes) {
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let index = 0;
    while (bytes >= 1024 && index < units.length - 1) {
        bytes /= 1024;
        index++;
    }
    return `${bytes.toFixed(2)} ${units[index]}`;
}